import 'package:adjg_flutter/ad_jg_ad.dart';
import 'package:adjg_flutter/ad_jg_base.dart';
import 'package:flutter/material.dart';

import 'key.dart';

class BannerPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _BannerState();
}

class _BannerState extends State<BannerPage> {
  ADJgFlutterBannerAd? _adJgFlutterBannerAd;
  bool _hasInitBanner = false;

  @override
  Widget build(BuildContext context) {
    if (_adJgFlutterBannerAd == null && _hasInitBanner == false) {
      MediaQueryData queryData = MediaQuery.of(context);
      _hasInitBanner = true;
      var width = queryData.size.width;
      var height = width / 320.0 * 50.0;
      _adJgFlutterBannerAd = ADJgFlutterBannerAd(
          posId: KeyManager.bannerPosid(), width: width, height: height);
      _adJgFlutterBannerAd!.loadAndShow();
      // 横幅加载成功回调
      _adJgFlutterBannerAd!.onSucced = (AdInfo adInfo) {
        print("横幅广告加载成功 platformName : " +
            adInfo.platformName +
            " ecpmPrecision : " +
            adInfo.ecpmPrecision +
            " ecpm : " +
            adInfo.ecpm.toString());
      };
      // 横幅加载失败回调
      _adJgFlutterBannerAd!.onFailed = (AdErrorInfo adErrorInfo) {
        removeBannerAd();
        print("横幅广告加载失败 errorCode : " +
            adErrorInfo.errorCode.toString() +
            " errorDescription : " +
            adErrorInfo.errorDescription);
      };
      // 横幅点击回调
      _adJgFlutterBannerAd!.onClicked = (AdInfo adInfo) {
        print("横幅广告点击 platformName : " +
            adInfo.platformName +
            " ecpmPrecision : " +
            adInfo.ecpmPrecision +
            " ecpm : " +
            adInfo.ecpm.toString());
      };
      // 横幅曝光回调
      _adJgFlutterBannerAd!.onExposed = (AdInfo adInfo) {
        print("横幅广告渲染成功 platformName : " +
            adInfo.platformName +
            " ecpmPrecision : " +
            adInfo.ecpmPrecision +
            " ecpm : " +
            adInfo.ecpm.toString());
      };
      // 横幅关闭回调
      _adJgFlutterBannerAd!.onClosed = (AdInfo adInfo) {
        removeBannerAd();
        print("横幅广告关闭成功 platformName : " +
            adInfo.platformName +
            " ecpmPrecision : " +
            adInfo.ecpmPrecision +
            " ecpm : " +
            adInfo.ecpm.toString());
      };
    }

    return Scaffold(
        appBar: AppBar(
          title: Text("BannerPage"),
        ),
        body: Center(
            child: (_adJgFlutterBannerAd == null
                ? Text("banner广告已关闭")
                : ADJgWidget(adView: _adJgFlutterBannerAd!))));
  }

  void removeBannerAd() {
    setState(() {
      releaseBannerAd();
    });
  }

  void releaseBannerAd() {
    _adJgFlutterBannerAd?.release();
    _adJgFlutterBannerAd = null;
  }

  @override
  void dispose() {
    releaseBannerAd();
    super.dispose();
  }
}
